import 'package:flutter/material.dart';
import 'package:logger/logger.dart';
import '../../models/carbon_footprint_record.dart';
import '../../services/carbon_footprint_service.dart';
import '../../state/auth_provider.dart';
import 'carbon_footprint_form_screen.dart';

/// 碳足迹记录列表页面
class CarbonFootprintListScreen extends StatefulWidget {
  const CarbonFootprintListScreen({super.key});

  @override
  State<CarbonFootprintListScreen> createState() => _CarbonFootprintListScreenState();
}

class _CarbonFootprintListScreenState extends State<CarbonFootprintListScreen> {
  final Logger _logger = Logger();
  final CarbonFootprintService _carbonFootprintService = CarbonFootprintService();
  
  List<CarbonFootprintRecord> _records = [];
  List<Map<String, dynamic>> _processTypes = [];
  bool _isLoading = false;
  String? _errorMessage;
  String _searchKeyword = '';
  int? _selectedProcessType;
  DateTime? _startDate;
  DateTime? _endDate;

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  /// 加载数据
  Future<void> _loadData() async {
    _logger.d('🔍 开始加载碳足迹记录数据');
    
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      // 并行加载记录和工艺类型
      final results = await Future.wait([
        _carbonFootprintService.getAllRecords(
          searchKeyword: _searchKeyword.isNotEmpty ? _searchKeyword : null,
          processType: _selectedProcessType,
          startDate: _startDate,
          endDate: _endDate,
        ),
        _carbonFootprintService.getProcessTypes(),
      ]);

      setState(() {
        _records = results[0] as List<CarbonFootprintRecord>;
        _processTypes = results[1] as List<Map<String, dynamic>>;
        _isLoading = false;
      });

      _logger.i('✅ 碳足迹记录数据加载成功: ${_records.length} 条记录');
    } catch (e) {
      _logger.e('❌ 加载碳足迹记录数据失败: $e');
      setState(() {
        _isLoading = false;
        _errorMessage = '加载数据失败: $e';
      });
    }
  }

  /// 搜索记录
  Future<void> _searchRecords(String keyword) async {
    _logger.d('🔍 开始搜索碳足迹记录: keyword=$keyword');
    
    setState(() {
      _searchKeyword = keyword;
      _isLoading = true;
    });

    try {
      final records = await _carbonFootprintService.getAllRecords(
        searchKeyword: keyword.isNotEmpty ? keyword : null,
        processType: _selectedProcessType,
        startDate: _startDate,
        endDate: _endDate,
      );

      setState(() {
        _records = records;
        _isLoading = false;
      });

      _logger.i('✅ 搜索碳足迹记录成功: 找到 ${records.length} 条记录');
    } catch (e) {
      _logger.e('❌ 搜索碳足迹记录失败: $e');
      setState(() {
        _isLoading = false;
        _errorMessage = '搜索失败: $e';
      });
    }
  }

  /// 删除记录
  Future<void> _deleteRecord(CarbonFootprintRecord record) async {
    _logger.d('🗑️ 开始删除碳足迹记录: ${record.recordName}');
    
    // 显示确认对话框
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: Text('确定要删除记录"${record.recordName}"吗？此操作不可恢复。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(true),
            style: TextButton.styleFrom(foregroundColor: Colors.red),
            child: const Text('删除'),
          ),
        ],
      ),
    );

    if (confirmed != true) return;

    try {
      final success = await _carbonFootprintService.deleteRecord(record.id!);
      
      if (success) {
        _logger.i('✅ 碳足迹记录删除成功');
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('记录"${record.recordName}"已删除')),
        );
        // 重新加载数据
        await _loadData();
      } else {
        _logger.w('⚠️ 碳足迹记录删除失败');
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('删除失败，请重试')),
        );
      }
    } catch (e) {
      _logger.e('❌ 删除碳足迹记录失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('删除失败: $e')),
      );
    }
  }

  /// 显示记录表单
  void _showRecordForm([CarbonFootprintRecord? record]) {
    _logger.d('📝 显示碳足迹记录表单: ${record?.recordName ?? '新增'}');
    
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => CarbonFootprintFormScreen(record: record),
      ),
    ).then((_) {
      // 表单关闭后重新加载数据
      _loadData();
    });
  }

  /// 构建搜索栏
  Widget _buildSearchBar() {
    return Container(
      padding: const EdgeInsets.all(16),
      child: Row(
        children: [
          Expanded(
            child: TextField(
              decoration: InputDecoration(
                hintText: '搜索记录名称、编号或位置...',
                prefixIcon: const Icon(Icons.search),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
                contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              ),
              onChanged: (value) {
                // 延迟搜索，避免频繁请求
                Future.delayed(const Duration(milliseconds: 500), () {
                  if (mounted) {
                    _searchRecords(value);
                  }
                });
              },
            ),
          ),
          const SizedBox(width: 8),
          IconButton(
            onPressed: () => _showFilterDialog(),
            icon: const Icon(Icons.filter_list),
            tooltip: '筛选',
          ),
        ],
      ),
    );
  }

  /// 显示筛选对话框
  void _showFilterDialog() {
    showDialog(
      context: context,
      builder: (context) => StatefulBuilder(
        builder: (context, setDialogState) => AlertDialog(
          title: const Text('筛选条件'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 工艺类型筛选
              DropdownButtonFormField<int>(
                decoration: const InputDecoration(
                  labelText: '工艺类型',
                  border: OutlineInputBorder(),
                ),
                value: _selectedProcessType,
                items: [
                  const DropdownMenuItem(
                    value: null,
                    child: Text('全部工艺'),
                  ),
                  ..._processTypes.map((type) => DropdownMenuItem(
                    value: type['id'] as int,
                    child: Text(type['type_name'] as String),
                  )),
                ],
                onChanged: (value) {
                  setDialogState(() {
                    _selectedProcessType = value;
                  });
                },
              ),
              const SizedBox(height: 16),
              // 日期范围筛选
              Row(
                children: [
                  Expanded(
                    child: TextFormField(
                      decoration: const InputDecoration(
                        labelText: '开始日期',
                        border: OutlineInputBorder(),
                      ),
                      readOnly: true,
                      controller: TextEditingController(
                        text: _startDate?.toString().split(' ')[0] ?? '',
                      ),
                      onTap: () async {
                        final date = await showDatePicker(
                          context: context,
                          initialDate: _startDate ?? DateTime.now(),
                          firstDate: DateTime(2020),
                          lastDate: DateTime.now(),
                        );
                        if (date != null) {
                          setDialogState(() {
                            _startDate = date;
                          });
                        }
                      },
                    ),
                  ),
                  const SizedBox(width: 8),
                  Expanded(
                    child: TextFormField(
                      decoration: const InputDecoration(
                        labelText: '结束日期',
                        border: OutlineInputBorder(),
                      ),
                      readOnly: true,
                      controller: TextEditingController(
                        text: _endDate?.toString().split(' ')[0] ?? '',
                      ),
                      onTap: () async {
                        final date = await showDatePicker(
                          context: context,
                          initialDate: _endDate ?? DateTime.now(),
                          firstDate: DateTime(2020),
                          lastDate: DateTime.now(),
                        );
                        if (date != null) {
                          setDialogState(() {
                            _endDate = date;
                          });
                        }
                      },
                    ),
                  ),
                ],
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () {
                setDialogState(() {
                  _selectedProcessType = null;
                  _startDate = null;
                  _endDate = null;
                });
              },
              child: const Text('清除'),
            ),
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () {
                Navigator.of(context).pop();
                _loadData(); // 应用筛选条件
              },
              child: const Text('应用'),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建记录列表项
  Widget _buildRecordItem(CarbonFootprintRecord record) {
    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
      child: ListTile(
        title: Text(
          record.recordName,
          style: const TextStyle(fontWeight: FontWeight.bold),
        ),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 4),
            Text('编号: ${record.recordCode}'),
            Text('工艺: ${record.processTypeName}'),
            Text('产能: ${record.productionCapacity.toStringAsFixed(2)} 吨/年'),
            Text('能耗: ${record.energyConsumption.toStringAsFixed(2)} kWh/吨'),
            Text('碳排放: ${record.carbonEmission.toStringAsFixed(2)} 吨CO2/吨'),
            if (record.location != null) Text('位置: ${record.location}'),
            Text('记录日期: ${record.recordDate.toString().split(' ')[0]}'),
          ],
        ),
        trailing: PopupMenuButton<String>(
          onSelected: (value) {
            switch (value) {
              case 'edit':
                _showRecordForm(record);
                break;
              case 'delete':
                _deleteRecord(record);
                break;
            }
          },
          itemBuilder: (context) => [
            const PopupMenuItem(
              value: 'edit',
              child: Row(
                children: [
                  Icon(Icons.edit, size: 16),
                  SizedBox(width: 8),
                  Text('编辑'),
                ],
              ),
            ),
            const PopupMenuItem(
              value: 'delete',
              child: Row(
                children: [
                  Icon(Icons.delete, size: 16, color: Colors.red),
                  SizedBox(width: 8),
                  Text('删除', style: TextStyle(color: Colors.red)),
                ],
              ),
            ),
          ],
        ),
        onTap: () {
          // 点击查看详情
          _showRecordForm(record);
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('碳足迹记录'),
        actions: [
          IconButton(
            onPressed: () => _loadData(),
            icon: const Icon(Icons.refresh),
            tooltip: '刷新',
          ),
        ],
      ),
      body: Column(
        children: [
          _buildSearchBar(),
          if (_errorMessage != null)
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(16),
              color: Colors.red.shade50,
              child: Text(
                _errorMessage!,
                style: TextStyle(color: Colors.red.shade700),
              ),
            ),
          Expanded(
            child: _isLoading
                ? const Center(child: CircularProgressIndicator())
                : _records.isEmpty
                    ? const Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(Icons.inbox_outlined, size: 64, color: Colors.grey),
                            SizedBox(height: 16),
                            Text(
                              '暂无碳足迹记录',
                              style: TextStyle(fontSize: 16, color: Colors.grey),
                            ),
                            SizedBox(height: 8),
                            Text(
                              '点击下方按钮添加第一条记录',
                              style: TextStyle(fontSize: 14, color: Colors.grey),
                            ),
                          ],
                        ),
                      )
                    : ListView.builder(
                        itemCount: _records.length,
                        itemBuilder: (context, index) => _buildRecordItem(_records[index]),
                      ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => _showRecordForm(),
        child: const Icon(Icons.add),
        tooltip: '添加记录',
      ),
    );
  }
} 